package cn.edu.sdjzu.xg.eagle.controller;

import cn.edu.sdjzu.xg.eagle.entity.School;
import cn.edu.sdjzu.xg.eagle.exception.BaseException;
import cn.edu.sdjzu.xg.eagle.factory.ServiceFactory;
import cn.edu.sdjzu.xg.eagle.service.SchoolService;
import cn.edu.sdjzu.xg.eagle.util.Condition;
import cn.edu.sdjzu.xg.eagle.util.ControllerHelper;
import cn.edu.sdjzu.xg.eagle.util.JSONUtil;
import cn.edu.sdjzu.xg.eagle.util.Pagination;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

/**
 * @author tg.si@188.com
 * @todo
 * @since 2022/10/12 18:56
 */
@WebServlet({"/school/*", "/school"})
public class SchoolReadCtrl extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(SchoolReadCtrl.class);
    /**
     * GET, localhost:8080/bysj/school/1, RESTful风格的URL查询id=1的学院
     * 把一个学院对象响应到前端
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置响应字符编码为UTF-8，以便正确响应汉字
        response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象message，以便往前端响应信息
        JSONObject message_jsonObj = new JSONObject();
        // 获得id
        //String id_str = request.getParameter("id");
        Integer id_int = null;
        try{
            String id_str = request.getPathInfo().substring(1);

            id_int = Integer.parseInt(id_str);
        }catch (Exception e) {
            //不可行
//            response.sendRedirect("/school/");
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "id缺失或不是整型");
            return;
        }
        try {
            School school = ServiceFactory.getService(SchoolService.class, "SchoolServiceImpl")
                    .find(id_int);
            String school_json = JSON.toJSONString(school,
                    JSONWriter.Feature.ReferenceDetection);
            response.getWriter().println(school_json);
        } catch (BaseException e) {
            message_jsonObj.put("message", e);
            response.getWriter().println(message_jsonObj);
            logger.error(e.getMessage());
        } catch (SQLException e) {
            message_jsonObj.put("message", "数据库操作异常");
            response.getWriter().println(message_jsonObj);
            logger.error(e.getMessage());
        } catch (Exception e) {
            message_jsonObj.put("message", "网络异常");
            response.getWriter().println(message_jsonObj);
            logger.error(e.getMessage());
        }
    }

    /**
     * PUT, http://localhost:8080/schoolRead.ctl
     * 把所有学院对象响应到前端
     */
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象message，以便往前端响应信息
        JSONObject message_jsonObj = new JSONObject();

        try {
//            Collection<School> schoolList = SchoolService.getInstance().findAll();
            Collection<School> schoolList = ServiceFactory.getService(SchoolService.class, "SchoolServiceImpl").findAll();
            String schools_json = JSON.toJSONString(schoolList,
                    JSONWriter.Feature.ReferenceDetection);
            //响应message到前端
            response.getWriter().println(schools_json);
////            message_jsonObj.put("records",schoolList);
//            response.getWriter().println(message_jsonObj);
        } catch (BaseException e) {
            message_jsonObj.put("message", e.getMessage());
            response.getWriter().println(message_jsonObj);
            logger.error(e.getMessage());
        } catch (SQLException e) {
            message_jsonObj.put("message", "数据库操作异常");
            response.getWriter().println(message_jsonObj);
            logger.error(e.getMessage());
        } catch (Exception e) {
            message_jsonObj.put("message", "网络异常");
            response.getWriter().println(message_jsonObj);
            logger.error(e.getMessage());
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //授权验证
//        String idInToken = JwtUtil.parseToken(request);
//        log.debug("id in token=" + idInToken);

        //创建JSON对象message_jsonObj，以便往前端响应信息
        JSONObject message_jsonObj = new JSONObject();

        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body解析为JSONObject对象，可能含有分页信息、查询条件
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //如果请求body为空
        if (req_jsonObj == null) {
            message_jsonObj.put("message", "未收到请求信息！");
            response.getWriter().println(message_jsonObj);
            return;
        }
        try {
            //读取分页信息，形成分页对象{"pagination":{"pageNo":1,"pageSize":2}}
            //将JSON字串解析为Pagination对象
            Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
            //分页获得所有学院
            Collection<School> schools = ServiceFactory.
                    getService(SchoolService.class, "SchoolServiceImpl").findAll(pagination);

//            String schools_json = JSON.toJSONString(
//                    schools, JSONWriter.Feature.ReferenceDetection);
            message_jsonObj.put("totalNum", pagination.getTotalNum());
            message_jsonObj.put("records", schools);
            //响应message_jsonObj到前端
            response.getWriter().println(message_jsonObj);
        } catch (BaseException e) {
            message_jsonObj.put("message", e.getMessage());
            response.getWriter().println(message_jsonObj);
            logger.error(e.getMessage());
        } catch (SQLException e) {
            message_jsonObj.put("message", "数据库操作异常");
            response.getWriter().println(message_jsonObj);
            logger.error(e.getMessage());
        } catch (Exception e) {
            message_jsonObj.put("message", "网络异常");
            response.getWriter().println(message_jsonObj);
        }
    }

    /**
     * 条件查询、分页响应
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //授权验证
//        String idInToken = JwtUtil.parseToken(request);
//        log.debug("id in token=" + idInToken);

        //创建JSON对象message_jsonObj，以便往前端响应信息
        JSONObject message_jsonObj = new JSONObject();
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body解析为JSONObject对象，可能含有分页信息、查询条件
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //如果请求body为空
        if (req_jsonObj == null) {
            message_jsonObj.put("message", "未收到请求信息！");
            response.getWriter().println(message_jsonObj);
            return;
        }
        try {
            //读取分页信息，形成分页对象{"pagination":{"pageNo":1,"pageSize":2}}
            //将JSON字串解析为Pagination对象
            Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
            //从请求JSONObject对象中读取键“conditionList”对应的值(描述查询条件的JSONArray对象)
            List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
            //分页获得所有学院
            Collection<School> schools = ServiceFactory.getService
                    (SchoolService.class,"SchoolServiceImpl").findAll(pagination, conditionList);

//            String schools_json = JSON.toJSONString(
//                    schools, JSONWriter.Feature.ReferenceDetection);
            message_jsonObj.put("totalNum", pagination.getTotalNum());
            message_jsonObj.put("records", schools);
            //响应message_jsonObj到前端
            response.getWriter().println(message_jsonObj);
        } catch (BaseException e) {
            message_jsonObj.put("message", e.getMessage());
            response.getWriter().println(message_jsonObj);
            logger.error(e.getMessage());
        } catch (SQLException e) {
            message_jsonObj.put("message", "数据库操作异常");
            response.getWriter().println(message_jsonObj);
            logger.error(e.getMessage());
        } catch (Exception e) {
            message_jsonObj.put("message", "网络异常");
            response.getWriter().println(message_jsonObj);
        }
    }

//    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
//            throws ServletException, IOException {
//
//        //授权验证
////        String idInToken = JwtUtil.parseToken(request);
////        log.debug("id in token=" + idInToken);
//
//        //创建JSON对象message_jsonObj，以便往前端响应信息
//        JSONObject message_jsonObj = new JSONObject();
//
//        //设置响应字符编码为UTF-8
//        response.setContentType("application/json;charset=UTF-8");
//        //将request body转换为JSON字串
//        String req_jsonStr = JSONUtil.getJSON(request);
//        //将request body解析为JSONObject对象，可能含有分页信息、查询条件
//        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
//        //如果请求body为空
//        if (req_jsonObj == null) {
//            message_jsonObj.put("message","未收到请求信息！");
//            response.getWriter().println(message_jsonObj);
//            return;
//        }
//
//        try {
//            //读取分页信息，形成分页对象
//            //示例{"pageNo":1,"pageSize":2}
//            //将JSON字串解析为Pagination对象
//            Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
//            //从请求JSONObject对象中读取键“conditionList”对应的值(描述查询条件的JSONArray对象)
//            List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
//            //响应多个教师信息，其中conditionList, pagination两个对象引用为空是可能的
//            this.responseSchools(response, pagination, conditionList);
//
//        }catch (SQLException e){
//            message_jsonObj.put("message", "数据库操作异常");
//            response.getWriter().println(message_jsonObj);
//            e.printStackTrace();
//        }catch(Exception e){
//            message_jsonObj.put("message", "网络异常");
//            response.getWriter().println(message_jsonObj);
//        }
//    }
}

